

/*
全体同步逻辑
1. 从数据库读取所有要同步的相册A
2. 读取本地所有的相册列表B 按ID转换为map，与A查找交集 C
3. 查找相册列表C中的每一项，加入到文件列表 D
4. 从数据库加载已同步文件列表 E，与D对比，选出所有D中未同步的文件，为F
4. 对F中的每一项目，执行以下过程

1. 从数据库读取所有已同步文件 S
2. 找到对应的本地数据库相册 Ba，读取其全部文件列表
3. 对比，生成差额即待上传文件列表 S2
4. 对S2 的每项，执行上传动作
*/
import 'package:cloudapp/bus/dtypes.dart';
import 'package:cloudapp/esdk/db.dart';
import 'package:cloudapp/esdk/esync.dart';
import 'package:photo_manager/photo_manager.dart';

Future<List<UploadFileInfo>> computeLeftAlbumFile(int sessionId) async {
  var pA = await DbStorage.i().findAllLocalAlbum(sessionId);
  //  var filter = FilterOptionGroup.empty();
  //  filter.setOption(AssetType.image, FilterOption(needTitle: true));
  var pB = await PhotoManager.getAssetPathList(
    hasAll: false,
  );

  Map<String, AssetPathEntity> mpB = {};
  for(var item in pB) {
    mpB[item.id] = item;
  }

  var pC = List<AlbumWithServerID>();
  for(var item in pA) {
    if(mpB.containsKey(item.albumId)) {
      pC.add(AlbumWithServerID(
        serverId: item.serverId,
        album: mpB[item.albumId],
      ));
    }
  }

  var pD = List<UploadTask>();
  for(var item in pC) {
    var fileList = await item.album.assetList;
    for(var file in fileList) {
      pD.add(UploadTask(
        serverAlbumId: item.serverId,
        localAlbumId: item.album.id,
        file: file,
        type: file.type,
        videoThumb: await file.thumbData,
        esync: ESync.i(),
      ));
    }
  }

  var pE = Set<String>();
  var syncFiles = await DbStorage.i().getAllSyncFile(sessionId);
  for(var item in syncFiles) {
    pE.add(item.sysId);
  }


  var left = List<UploadFileInfo>();
  for(var item in pD) {
    if(!pE.contains(item.file.id)) {
      // 未上传
      var fType = FileType.Other;
      switch(item.type) {
        case AssetType.audio:
          fType = FileType.Audio;
          break;
        case AssetType.image:
          fType = FileType.Picture;
          break;
        case AssetType.other:
          fType = FileType.Other;
          break;
        case AssetType.video:
          fType = FileType.Video;
          break;
      }
      var rawFile = await item.file.originFile;
      left.add(UploadFileInfo(
        serverAlbumId: item.serverAlbumId,
        localAlbumId: item.localAlbumId,
        localFileId: item.file.id,
        userId: ESync.i().userId,
        sessionId: sessionId,
        token: ESync.i().accessToken,
        baseHost: ESync.i().getServerHost(),
        fileName: item.file.title,
        filePath: rawFile.path,
        type: fType,
        videoThumb: item.videoThumb,
      ));
    }
  }

  print('diff albums, total ${left.length}');
  return left;
}
